package mx.frantor.catalogos.daoimp;

import java.math.BigInteger;
import java.util.List;
import java.util.StringTokenizer;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import flex.messaging.io.ArrayCollection;

import mx.frantor.catalogos.dao.OrdenesDeCompraDAO;
import mx.frantor.catalogos.entitys.OrdendecompramateriaprimaEntity;
import mx.frantor.catalogos.entitys.OrdenesDeCompraEntity;
import mx.frantor.util.HibernateUtil;

public class OrdenesDeCompraDAOImpl implements OrdenesDeCompraDAO {
	String errRslt;


	@Override
	public String agregarOrdenesDeCompra(
			OrdenesDeCompraEntity nuevoOrdenesDeCompra) {
		String e = "";
		Session session = HibernateUtil.getSessionFactory()
				.getCurrentSession();
		
		session.beginTransaction();
		try {
		session.save(nuevoOrdenesDeCompra);
		session.flush();
		session.getTransaction().commit();
		e = nuevoOrdenesDeCompra.getIdOrdenDeCompra().toString();
		} catch (Exception x) {
			//e.printStackTrace();
			session.getTransaction().rollback();
			e = x.getMessage();
			//return e.toString();
		}

		HibernateUtil.getSessionFactory().getCurrentSession().close();
		return e;
	}
	
	@Override
	public String agregarOrdenDeCompraConDetalle(OrdenesDeCompraEntity nuevaOrden, ArrayCollection ordUtil) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		try{
			session.save(nuevaOrden);//<<---Guardamos en la DB
			long idDetOrd = nuevaOrden.getIdOrdenDeCompra();
			
			//System.out.println("Size FlexCollection: " + reqUtil.size() + " Vals: " + reqUtil);
			String cantidadProd;
			String idPROD;
			for(int i = 0; i < ordUtil.size(); i++){
				StringTokenizer token = new StringTokenizer(String.valueOf(ordUtil.get(i).toString()),"=,");
				token.nextToken();
				idPROD = token.nextToken();
				token.nextToken();
				cantidadProd = token.nextToken();
				System.out.println(cantidadProd);
			
				
				//System.out.println("\nValToken: " + cantidadProd +" ::> "+idPROD);
				
				OrdendecompramateriaprimaEntity detalleOrdEntity = new OrdendecompramateriaprimaEntity();
				detalleOrdEntity.setIdOrdenDeCompra(idDetOrd);
				detalleOrdEntity.setIdMateria(Long.valueOf(idPROD));
				detalleOrdEntity.setCantidad(Long.valueOf(cantidadProd));
				session.save(detalleOrdEntity);
				
			}

			session.flush();
			session.getTransaction().commit(); //<--Realizamos commit de operacion en db
			errRslt = String.valueOf(idDetOrd);
			
		}catch (Exception e) {
			
			session.getTransaction().rollback();
			errRslt = e.getMessage();
			System.out.println("Error en agrega Requisicon con detalle implement: " + errRslt);
			
		}
		HibernateUtil.getSessionFactory().getCurrentSession().close();
		return errRslt;
	}

	
	@SuppressWarnings("unchecked")
	@Override
	public BigInteger getMaxIdRequisicion() {
		BigInteger max = null;
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		try{
		String qry = "select max(idrequisiciones) as idrequisiciones from requisiciones";
		SQLQuery query = session.createSQLQuery(qry);
		//query.addEntity(Long.class);
		List<BigInteger> requisicion = query.list();
		session.flush();
		max = requisicion.get(0);
		}catch (Exception e) {
			//max=0;
			System.out.println(e.toString());
			e.printStackTrace();
		}
		HibernateUtil.getSessionFactory().getCurrentSession().close();
		return max;
	}
	@SuppressWarnings("unchecked")
	@Override
	public BigInteger getMaxConsRequisicion() {
		BigInteger max = null;
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		try{
		String qry = "select max(consecutivo) as consecutivo from requisiciones";
		SQLQuery query = session.createSQLQuery(qry);
		//query.addEntity(Long.class);
		List<BigInteger> requisicion = query.list();
		session.flush();
		max = requisicion.get(0);
		}catch (Exception e) {
			//max=0;
			System.out.println(e.toString());
			e.printStackTrace();
		}
		HibernateUtil.getSessionFactory().getCurrentSession().close();
		return max;
	}
	@Override
	public String modificarOrdenesDeCompra(
			OrdenesDeCompraEntity modificarOrdenesDeCompra) {
		String e = "";
		Session session = HibernateUtil.getSessionFactory()
				.getCurrentSession();
	
		session.beginTransaction();
		try {
			OrdenesDeCompraEntity OrdenCompTemp = (OrdenesDeCompraEntity) session.get(
					OrdenesDeCompraEntity.class, modificarOrdenesDeCompra.getIdOrdenDeCompra());
		session.flush();
		session.evict(OrdenCompTemp);
		session.update(modificarOrdenesDeCompra);
		session.getTransaction().commit();
		} catch (Exception x) {
			//e.printStackTrace();
			session.getTransaction().rollback();
			e = x.getMessage();
			//return e.toString();
		}
		HibernateUtil.getSessionFactory().getCurrentSession().close();
		return e;
	}

	@Override
	public String eliminarOrdenesDeCompra(Long idOrdenesDeCompra) {
		String e = "";
		Session session = HibernateUtil.getSessionFactory()
				.getCurrentSession();
		

			// TODO Auto-generated method stub			
			session.beginTransaction();
			try {
				OrdenesDeCompraEntity OrdenCompElimina = (OrdenesDeCompraEntity) session.get(
						OrdenesDeCompraEntity.class, idOrdenesDeCompra);
			session.delete(OrdenCompElimina);
			session.getTransaction().commit();
		} catch (Exception x) {
			//e.printStackTrace();
			session.getTransaction().rollback();
			e = x.getMessage();
			//return e.toString();
		}
		//HibernateUtil.getSessionFactory().getCurrentSession().close();
		HibernateUtil.getSessionFactory().getCurrentSession().close();
		return e;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<OrdenesDeCompraEntity> getTodosOrdenesDeCompraActivas() {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<OrdenesDeCompraEntity> OrdenComp = session.createCriteria(OrdenesDeCompraEntity.class).list();
		HibernateUtil.getSessionFactory().getCurrentSession().close();
		return OrdenComp;
	}

	@SuppressWarnings("unchecked")
	@Override
	public OrdenesDeCompraEntity getOrdenesDeComprasId(Long idOrdenesDeCompra) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<OrdenesDeCompraEntity> OrdenComp = (List<OrdenesDeCompraEntity>) session.createCriteria(OrdenesDeCompraEntity.class)
				.add(Restrictions.eq("IdOrdenDeCompra", idOrdenesDeCompra))
				.setFetchSize(1).list();
		HibernateUtil.getSessionFactory().getCurrentSession().close();
		if(OrdenComp==null){
			return null;
		}else{
			return OrdenComp.get(0);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<OrdenesDeCompraEntity> getOrdenesDeCompraPorId(
			Long idOrdenesDeCompra) {
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			session.beginTransaction();
			List<OrdenesDeCompraEntity> OrdenComp = (List<OrdenesDeCompraEntity>) session.createCriteria(OrdenesDeCompraEntity.class)
					.add(Restrictions.eq("IdOrdenDeCompra", idOrdenesDeCompra))
					.list();
			HibernateUtil.getSessionFactory().getCurrentSession().close();
			return OrdenComp;
	}

}
